<?php
namespace App\Services\Work;

use Illuminate\Support\Facades\DB;
use App\Models\System\User;
use App\Models\System\Term;
use App\Models\ActivityInfo;
use App\Models\Teachers;
use App\Models\DictionaryItem;
use App\Models\EventStatistics;
use App\Models\Participant;
use App\Models\FormInstance;
use App\Models\File;
use App\Models\SystemTask;
use App\Models\System\Tasks;
use Illuminate\Database\Eloquent\Builder;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Controllers\Excel\ExcelExport;

class InWorkService{

    /** @var \App\Repositories\System\ActivityRepository $activityRepository */
    private $activityRepository;

    public function __construct()
    {
        $this->activityRepository = app('activityRepository');
    }

    /**
     * 列表
     * @author lxy
     * @datetime 2023-03-03
     */
    public function getInWorkList($request)
    {
        $limit = $request['limit'] ?? 10;
        $where = [];
        $user_id = auth()->user()->id;
        $role_id = auth()->user()->cur_role_id;
        //dd($role_id);

        !empty($request['search']['data_version_id'])   && $where[] = ['activity_info.data_version_id','=',$request['search']['data_version_id']];
        //!empty($request['search']['level'])     && $where[] = ['activity_info.level','like','%'.$request['search']['level'].'%'];
        !empty($request['search']['name'])     && $where[] = ['activity_info.name','like','%'.$request['search']['name'].'%'];
        !empty($request['search']['nickname'])     && $where[] = ['d.nickname','like','%'.$request['search']['nickname'].'%'];
        !empty($request['search']['compere'])     && $where[] = ['c.compere','like','%'.$request['search']['compere'].'%'];
        !empty($request['search']['status'])     && $where[] = ['b.status','=',$request['search']['status']];
        if(!empty($request['search']['date'])){
            $created_at = explode(' - ',$request['search']['date']);
            $where[] = ['activity_info.date','>=',$created_at[0]];
            $where[] = ['activity_info.date','<=',$created_at[1]];
        }

        //非管理员只能看到自己提交的数据
        // if(!is_check(190)){
        //     $where[] = ['activity_info.creator_id','=',$user_id];
        // }
        $where[] = ['activity_info.deleted','=',0];

        $where[] = ['activity_info.activity_category','=','IMPORTANTWORK_IN_SCHOOL_TABLE'];

        $result = ActivityInfo::select('b.data_version_name','activity_info.id','activity_info.name','activity_info.is_push',
            'activity_info.begin_date','activity_info.end_date','activity_info.level','activity_info.grade',
            'activity_info.category','activity_info.proof_material','b.status','c.participant','c.compere',
            'd.nickname','activity_info.teacher_name','activity_info.school_name','activity_info.date','activity_info.creator_id')
                ->leftJoin('form_instance as b' ,'activity_info.form_instance_id','=','b.id')
                ->leftJoin('event_statistics as c','c.activity_info_id','=','activity_info.id')
                ->leftJoin('users as d','activity_info.creator_id','=','d.id')
            ->leftJoin('participant as p', 'activity_info.id', '=', 'p.activity_info_id')
                ->where($where)
                ->with('participants')
            ->when(isset($request['user_id']) && !empty($request['user_id']), function($query) use($request){//处理档案袋只查看自己创建或者主持人参与教师的数据
                $query->whereRaw("((`activity_info`.`creator_id` = ".$request['user_id'].") or (`p`.`user_id` = ".$request['user_id']." and `b`.`status` != 'FILL_IN')) and b.status = 'PASS'");
            })
            ->when(!isset($request['user_id']), function($q) use($request) {
                $q->manageable();
            })
//                ->when(!in_array($role_id,[1,11]),function($q) use($user_id){
//                    //非校长，管理员能看自己
//                    return $q->whereHas('participants', function (Builder $query) use($user_id) {
//                        $query->where('user_id', $user_id);
//                    });
//                })
                ->when(!empty($request['search']['materials_date']),function($q) use($request){
                    return $q->whereRaw("activity_info.data_version_id in ({$request['search']['materials_date']})");
                })
                ->orderBy('activity_info.created_at','desc')
                ->groupBy('activity_info.id')
                ->paginate($limit)
                ->toArray();
     //dd($result);
        $result['limit'] = $limit;

        return $result;
    }

    /**
     * 导出
     * @author lxy
     * @datetime 2023-02-24
     */
    public function exportInWork($request)
    {
        $where = [];
        $user_id = auth()->user()->id;
        $role_id = auth()->user()->cur_role_id;
        //dd($role_id);

        !empty($request['search']['data_version_id'])   && $where[] = ['activity_info.data_version_id','=',$request['search']['data_version_id']];
        //!empty($request['search']['level'])     && $where[] = ['activity_info.level','like','%'.$request['search']['level'].'%'];
        !empty($request['search']['name'])     && $where[] = ['activity_info.name','like','%'.$request['search']['name'].'%'];
        !empty($request['search']['nickname'])     && $where[] = ['d.nickname','like','%'.$request['search']['nickname'].'%'];
        !empty($request['search']['compere'])     && $where[] = ['c.compere','like','%'.$request['search']['compere'].'%'];
        !empty($request['search']['status'])     && $where[] = ['b.status','=',$request['search']['status']];
        if(!empty($request['search']['date'])){
            $created_at = explode(' - ',$request['search']['date']);
            $where[] = ['activity_info.date','>=',$created_at[0]];
            $where[] = ['activity_info.date','<=',$created_at[1]];
        }

        //非管理员只能看到自己提交的数据
        // if(!is_check(190)){
        //     $where[] = ['activity_info.creator_id','=',$user_id];
        // }
        $where[] = ['activity_info.deleted','=',0];

        $where[] = ['activity_info.activity_category','=','IMPORTANTWORK_IN_SCHOOL_TABLE'];

        $result = ActivityInfo::select('b.data_version_name','activity_info.id','activity_info.name','activity_info.begin_date','activity_info.end_date','activity_info.level','activity_info.grade','activity_info.category','b.status','c.participant','c.compere','d.nickname','activity_info.teacher_name','activity_info.school_name','activity_info.date')
                ->leftJoin('form_instance as b' ,'activity_info.form_instance_id','=','b.id')
                ->leftJoin('event_statistics as c','c.activity_info_id','=','activity_info.id')
                ->leftJoin('users as d','activity_info.creator_id','=','d.id')
                ->where($where)
                ->with('participants')
                ->when(!in_array($role_id,[1,6]),function($q) use($user_id){
                    //非校长，管理员能看自己
                    return $q->whereHas('participants', function (Builder $query) use($user_id) {
                        $query->where('user_id', $user_id);
                    });
                })
                ->when(!empty($request['search']['materials_date']),function($q) use($request){
                    return $q->whereRaw("activity_info.data_version_id in ({$request['search']['materials_date']})");
                })
                ->orderBy('activity_info.created_at','desc')
                ->get()
                ->toArray();

        $field_name = ['学年学期','学校重要工作','日期','主持人','参与人','创建人'];
        $data = [];
        foreach($result as $k=>$v){
            $data[$k][] = $v['data_version_name'] === null?'':$v['data_version_name'];
            $data[$k][] = $v['name'];
            $data[$k][] = $v['date'];
            $data[$k][] = $v['compere'];
            $data[$k][] = count($v['participants']);
            $data[$k][] = $v['nickname'];
        }
        array_unshift($data,$field_name);

        $file_name = md5(auth()->user()->id.time()).'.xlsx';
        Excel::store(new ExcelExport($data), $file_name, 'excel');
        return [
            'file_name' => $file_name,
        ];
    }

    /**
     * 添加数据
     * @author lxy
     * @datetime 2023-03-03
     */
    public function addInWork($request)
    {
        $id = !empty($request['id'])?$request['id']:0;
        $form_instance_id = !empty($request['form_instance_id'])?$request['form_instance_id']:0;
        $user_id = auth()->user()->id;

        //学期名称
        $data_versions = Term::where('id',$request['data_version_id'])->first()->toArray();

        //文件
        $files = !empty($request['files'])?[$request['files']]:'';
        //参与教师
        $participant = !empty($request['participant'])?$request['participant']:'';
        $participant_id = !empty($request['participant_id'])?$request['participant_id']:'';
        //主持人
        $compere = !empty($request['compere'])?$request['compere']:'';
        $compere_id = !empty($request['compere_id'])?$request['compere_id']:'';
        $status = $request['status'] == 1?'PASS':'FILL_IN';
        unset($request['files'],$request['file'],$request['participant'],$request['participant_id'],$request['id'],$request['status'],$request['compere'],$request['compere_id']);
        if(empty($request['date'])) unset($request['date']);


        //已经提交过的数据不能保存
        if($status == 'FILL_IN'){
            if($id){
                $fi_status = FormInstance::where('id',$form_instance_id)->value('status');
                if($fi_status != 'FILL_IN'){
                    throw new \Exception('已提交过的数据不能继续保存');
                }
            }
        }
        try{
            DB::beginTransaction();
            $filesArr = [];
            //文件附件
            if($files){
                $proof_material = $this->activityRepository->dealUploadFile($files);
                $filesArr = array_column(json_decode($files[0],true)?:[], 'files_id');
            }
            $activity   =   '';
//            unset($request['s']);
            //添加
            if(!$id){
                //审核
                $formInstance = FormInstance::create([
                    'form_key'=>'IMPORTANTWORK_IN_SCHOOL_OPERATION',
                    'type'=>'ActivityCreate',
                    'owner_id'=>$user_id,
                    'status'=>$status,
                   // 'display_mode'=>$status == 'REVIEW'?'REVIEW':'EDIT',
                    'data_version_id'=>$request['data_version_id'],
                    'data_version_name'=>$data_versions['title'],
                    'creator_id'=>$user_id,
                ]);

                $request['creator_id'] = $user_id;
                $request['activity_category'] = 'IMPORTANTWORK_IN_SCHOOL_TABLE';
                $request['proof_material'] = $files?json_encode($proof_material):'';
                $request['form_instance_id'] = $formInstance->id;
                $activity = ActivityInfo::create(array_filter($request));
                $id = $activity->id;

            }else{  //编辑

                $formInstance = FormInstance::where('id',$form_instance_id)->first();

                // if($formInstance->status == 'FILL_IN' && $status == 'REVIEW'){
                //     FormInstance::where('id',$form_instance_id)->update(['status'=>$status]);
                // }else if($formInstance->status  == 'REVIEW_FAIL' && $status == 'REVIEW'){
                     FormInstance::where('id',$form_instance_id)->update(['status'=>$status]);
                // }

                if($files){
                    $request['proof_material'] = $files?json_encode($proof_material):'';
                }
                $request['updater_id'] = $user_id;

                FormInstance::where('id',$form_instance_id)->update(['data_version_id'=>$request['data_version_id'],'data_version_name'=>$data_versions['title']]);
                ActivityInfo::where('id',$id)->update(array_filter($request));

            }

            //添加待办事项
            // if($status=='REVIEW'){
            //     //处理有驳回的数据
            //     Tasks::where('form_key','IMPORTANTWORK_IN_SCHOOL_TABLE')->where('form_id',$id)->where('status',1)->where('type',3)->update(['status'=>2]);
            //     if(!Tasks::where('form_key','IMPORTANTWORK_IN_SCHOOL_TABLE')->where('form_id',$id)->where('status',1)->first()){
            //         $time = date('Y-m-d H:i:s');
            //         Tasks::create([
            //             'name'=>'【'.$data_versions['title'].'】重要工作-校内工作审核',
            //             'data_version_id'=>$request['data_version_id'],
            //             'form_id'=>$id,
            //             'form_key'=>'IMPORTANTWORK_IN_SCHOOL_TABLE',
            //             'start_date'=>$time,
            //             'end_date'=>$time,
            //             'creator_id'=>$user_id,
            //             'creator_name'=>auth()->user()->nickname,
            //             'param'=>'?id='.$id,
            //             'url'=>'/work/inwork/check',
            //             'menu_id'=>189
            //         ]);
            //     }
            // }

           //参与人员 或 主持人
           if($participant || $compere){
                EventStatistics::updateOrCreate(
                    ['activity_info_id' => $id],
                    [
                    'type' => '重要工作',
                    'child_type' => '校内',
                    'name' => !empty($request['name'])?$request['name']:'',
                    'level' => !empty($request['level'])?json_decode($request['level'],true)[0]['selectValue']:'',
                    'compere' => $compere,
                    'participant' => $participant,
                    'date' => date('Y-m-d'),
                    'data_version_id' => $request['data_version_id'],
                ]);

                $data = [];$data2 = [];
                if(!empty($participant_id)){
                    Participant::where('activity_info_id',$id)->where('participant_type','PARTICIPANT')->delete();
                    foreach($participant_id as $k=>$v){
                        $data[$k]['created_at'] = date('Y-m-d H:i:s');
                        $data[$k]['creator_id'] = $user_id;
                        $data[$k]['updated_at'] = date('Y-m-d H:i:s');
                        $data[$k]['updater_id'] = $user_id;
                        $data[$k]['activity_info_id'] = $id;
                        $data[$k]['activity_category'] = 'IMPORTANTWORK_IN_SCHOOL_TABLE';
                        $data[$k]['user_id'] = $v;
                        $data[$k]['participant_type'] = 'PARTICIPANT';
                        $data[$k]['name'] = !empty($request['name'])?$request['name']:'';
                    }
                    Participant::insert($data);
                }
                if(!empty($compere_id)){
                    Participant::where('activity_info_id',$id)->where('participant_type','COMPERE')->delete();
                    foreach($compere_id as $k=>$v){
                        $data2[$k]['created_at'] = date('Y-m-d H:i:s');
                        $data2[$k]['creator_id'] = $user_id;
                        $data2[$k]['updated_at'] = date('Y-m-d H:i:s');
                        $data2[$k]['updater_id'] = $user_id;
                        $data2[$k]['activity_info_id'] = $id;
                        $data2[$k]['activity_category'] = 'IMPORTANTWORK_IN_SCHOOL_TABLE';
                        $data2[$k]['user_id'] = $v;
                        $data2[$k]['participant_type'] = 'COMPERE';
                        $data2[$k]['name'] = !empty($request['name'])?$request['name']:'';
                    }
                    Participant::insert($data2);
                }

            }

            //关联推优文件处理
            if (!empty($filesArr)){
                $activity = $activity?:ActivityInfo::find($id);
                $activity->files_id = $filesArr;
            }

            DB::commit();
            return $id;

        }catch(\Exception $e){
            DB::rollback();
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 审核
     * @author lxy
     * @datetime 2023-02-24
     */
    public function checkInWork($request)
    {

        if(empty($request['status'])) {
            throw new \Exception('必须勾选审核结果！');
        }
        $result = FormInstance::where('id',$request['form_instance_id'])->update([
            'status'=>$request['status'],
            'comment'=>$request['comment'],
            'updater_id'=>auth()->user()->id,
        ]);

        //修改待办事项
        Tasks::where('form_key','IMPORTANTWORK_IN_SCHOOL_TABLE')->where('form_id',$request['id'])->update(['status'=>2]);

        //如果是驳回，重新给申报人发起待办事项
        if($request['status']== 'REVIEW_FAIL'){
            $task = Tasks::where('form_key','IMPORTANTWORK_IN_SCHOOL_TABLE')->where('form_id',$request['id'])->where('type',1)->orderBy('created_at','desc')->first();
            if(!$task){
                return [];
            }
            $task = $task->toArray();
            Tasks::create([
                'name'=>$task['name'].'驳回',
                'type' => 3,
                'data_version_id'=>$task['data_version_id'],
                'form_id'=>$task['form_id'],
                'form_key'=>'IMPORTANTWORK_IN_SCHOOL_TABLE',
                'start_date'=>date('Y-m-d H:i:s'),
                'end_date'=>date('Y-m-d H:i:s'),
                'c_user_id' => $task['creator_id'],
                'c_user_name' => $task['creator_name'],
                'creator_id'=>auth()->user()->id,
                'creator_name'=>auth()->user()->nickname,
                'param'=>$task['param'],
                'url'=>'/work/inwork/add',
                'menu_id'=>187
            ]);
        }


        return $result;
    }


    /**
     * 删除
     * @author lxy
     * @datetime 2023-03-07
     */
    public function delInWork($request)
    {
        $id = $request['id'];
       // Tasks::where('form_key','IMPORTANTWORK_IN_SCHOOL_TABLE')->where('form_id',$id)->where('status',1)->delete();
        return ActivityInfo::where('id',$id)->update(['deleted'=>1]);
    }

}
